<template>
  <div class="component-four">
    <div class="select-container">
      <select v-model="selectedYear" @change="fetchData">
        <option v-for="year in years" :key="year" :value="year">{{ year }}</option>
      </select>
      <select v-model="selectedCountry" @change="fetchData">
        <option v-for="country in countries" :key="country" :value="country">{{ country }}</option>
      </select>
    </div>

    <div class="liquid-charts">
      <div class="liquid-chart">
        <h3>获奖总比</h3>
        <div :id="'total-chart'" class="chart"></div>
        <div :id="'total-pie'" class="pie-chart"></div>
      </div>
      <div class="liquid-chart">
        <h3>获金牌占比</h3>
        <div :id="'gold-chart'" class="chart"></div>
        <div :id="'gold-pie'" class="pie-chart"></div>
      </div>
      <div class="liquid-chart">
        <h3>获银牌占比</h3>
        <div :id="'silver-chart'" class="chart"></div>
        <div :id="'silver-pie'" class="pie-chart"></div>
      </div>
      <div class="liquid-chart">
        <h3>获铜牌占比</h3>
        <div :id="'bronze-chart'" class="chart"></div>
        <div :id="'bronze-pie'" class="pie-chart"></div>
      </div>
    </div>

    <div class="top-ten-section">
      <select v-model="selectedMedalType" @change="updateTopTen">
        <option value="gold">金牌</option>
        <option value="silver">银牌</option>
        <option value="bronze">铜牌</option>
      </select>
      <table class="top-ten-table">
        <thead>
          <tr>
            <th>姓名</th>
            <th>奖牌数量</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(athlete, index) in currentTopTen" :key="index">
            <td>{{ athlete.Name }}</td>
            <td class="medals">
              <span v-for="n in getMedalCount(athlete)" :key="n"
                    :class="['medal', selectedMedalType]"></span>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import axios from 'axios'
import * as echarts from 'echarts'
import 'echarts-liquidfill'

const years = ref([])
const countries = ref([])
const selectedYear = ref('不选择')
const selectedCountry = ref('不选择')
const selectedMedalType = ref('gold')
const currentTopTen = ref([])

let charts = {
  total: null,
  totalPie: null,
  gold: null,
  goldPie: null,
  silver: null,
  silverPie: null,
  bronze: null,
  bronzePie: null
}

// 获取年份列表
const fetchYears = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:5000/get_games_list')
    if (response.data.success) {
      years.value = response.data.data
    }
  } catch (error) {
    console.error('获取年份列表失败：', error)
  }
}

// 获取国家列表
const fetchCountries = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:5000/select_list_region')
    if (response.data.success) {
      countries.value = response.data.data
    }
  } catch (error) {
    console.error('获取国家列表失败：', error)
  }
}

// 初始化图表
const initCharts = () => {
  charts.total = echarts.init(document.getElementById('total-chart'))
  charts.totalPie = echarts.init(document.getElementById('total-pie'))
  charts.gold = echarts.init(document.getElementById('gold-chart'))
  charts.goldPie = echarts.init(document.getElementById('gold-pie'))
  charts.silver = echarts.init(document.getElementById('silver-chart'))
  charts.silverPie = echarts.init(document.getElementById('silver-pie'))
  charts.bronze = echarts.init(document.getElementById('bronze-chart'))
  charts.bronzePie = echarts.init(document.getElementById('bronze-pie'))
}

// 更新水滴图
const updateLiquidChart = (chart, value, color = '#1890ff') => {
  const option = {
    series: [{
      type: 'liquidFill',
      data: [value / 100],
      radius: '80%',
      color: [color],
      label: {
        formatter: `${value.toFixed(2)}%`
      },
      backgroundStyle: {
        color: 'transparent'
      },
      outline: {
        show: true,
        borderDistance: 5,
        itemStyle: {
          borderColor: color,
          borderWidth: 2
        }
      }
    }]
  }
  chart.setOption(option)
}

// 更新饼图
const updatePieChart = (chart, data, title) => {
  const option = {
    title: {
      text: title,
      left: 'center',
      top: 10,
      textStyle: {
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}%'
    },
    series: [{
      type: 'pie',
      radius: ['40%', '70%'],
      data: data.map(item => ({
        name: item.Sport,
        value: item[Object.keys(item).find(key => key.includes('proportion'))]
      })),
      label: {
        show: false
      }
    }]
  }
  chart.setOption(option)
}

// 获取奖牌数量
const getMedalCount = (athlete) => {
  if (selectedMedalType.value === 'gold') return athlete.gold_count
  if (selectedMedalType.value === 'silver') return athlete.silver_count
  return athlete.bronze_count
}

const responseData = ref(null)

// 获取并更新数据
const fetchData = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:5000/medal_analysis', {
      params: {
        year: selectedYear.value,
        country: selectedCountry.value
      }
    })

    if (response.data.success) {
      const { data } = response.data
      responseData.value = data  // 保存响应数据

      // 更新水滴图和饼图
      updateLiquidChart(charts.total, data.count_data.total_medal_proportion)
      updatePieChart(charts.totalPie, data.count_data.sport_medal_count, '各项目获奖占比')

      updateLiquidChart(charts.gold, data.gold_count_data.total_medal_proportion, '#FFD700')
      updatePieChart(charts.goldPie, data.gold_count_data.sport_medal_count, '各项目获金牌占比')

      updateLiquidChart(charts.silver, data.silver_count_data.total_medal_proportion, '#C0C0C0')
      updatePieChart(charts.silverPie, data.silver_count_data.sport_medal_count, '各项目获银牌占比')

      updateLiquidChart(charts.bronze, data.bronze_count_data.total_medal_proportion, '#CD7F32')
      updatePieChart(charts.bronzePie, data.bronze_count_data.sport_medal_count, '各项目获铜牌占比')

      // 更新前十名列表
      updateTopTen()
    }
  } catch (error) {
    console.error('获取数据失败：', error)
  }
}

// 更新前十名列表
const updateTopTen = () => {
  if (!responseData.value) return
  const typeMap = {
    gold: 'top_ten_gold',
    silver: 'top_ten_silver',
    bronze: 'top_ten_bronze'
  }
  currentTopTen.value = responseData.value[typeMap[selectedMedalType.value]]
}

// 处理窗口大小变化
const handleResize = () => {
  Object.values(charts).forEach(chart => chart?.resize())
}

onMounted(async () => {
  await Promise.all([fetchYears(), fetchCountries()])
  initCharts()
  fetchData()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  Object.values(charts).forEach(chart => chart?.dispose())
})
</script>

<style scoped>
.component-four {
  padding: 20px;
}

.select-container {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

select {
  padding: 8px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  width: 200px;
}

.liquid-charts {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

.liquid-chart {
  text-align: center;
}

.chart {
  height: 200px;
  margin-bottom: 20px;
}

.pie-chart {
  height: 200px;
}

.top-ten-section {
  margin-top: 30px;
}

.top-ten-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

th, td {
  border: 1px solid #dcdfe6;
  padding: 12px;
  text-align: left;
}

th {
  background-color: #f5f7fa;
}

.medals {
  display: flex;
  gap: 5px;
}

.medal {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: inline-block;
}

.medal.gold {
  background-color: #FFD700;
}

.medal.silver {
  background-color: #C0C0C0;
}

.medal.bronze {
  background-color: #CD7F32;
}
</style>
